
package com.funo.government.info.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.params.CookieSpecPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 网络操作工具类
 * 
 * @author wangjie
 */
public class NetUtils {

    /**
     * 无连接
     */
    public static final int STATE_CONNECT_NONE = 0;

    /**
     * WIFI连接
     */
    public static final int STATE_CONNECT_WIFI = 1;

    /**
     * 移动网络 2G/3G
     */
    public static final int STATE_CONNECT_MOBILE = 2;

    private static final int TIMEOUT = 100000;

    private static final String TAG = "NetUtils";

    private static final String ENCODEING = "UTF-8";

    private static final int IO_BUFFER_SIZE = 8 * 1024;

    /**
     * 判断网络是否连接
     * 
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        final ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
            return false;
        }
        return true;
    }

    /**
     * 获取当前网络连接状态
     * 
     * @param context
     * @return 常量 STATE_CONNECT_NONE：无连接， STATE_CONNECT_WIFI：WIFI连接,
     *         STATE_CONNECT_MOBILE：移动网络 2G/3G
     */
    public static int getNetConnectState(Context context) {
        final ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (networkInfo != null && networkInfo.isConnected()) {
            return STATE_CONNECT_WIFI;
        }
        networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (networkInfo != null && networkInfo.isConnected()) {
            return STATE_CONNECT_MOBILE;
        }
        return STATE_CONNECT_NONE;
    }

    /**
     * 访问指定url，并获取inputStream
     * 
     * @param urlString
     * @return
     * @throws IOException
     */
    public static InputStream doGetStream(String urlString) throws IOException {

        InputStream is = null;
        disableConnectionReuseIfNecessary();
        HttpClient client = getHttpClient();
        HttpGet httpGet = bulidHttpGet(urlString);

        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            return null;
        }
        is = response.getEntity().getContent();

        // HttpURLConnection connection = getConnection(urlString);
        // connection.setRequestMethod("GET");
        // connection.connect();
        //
        // final int statusCode = connection.getResponseCode();
        // if (statusCode != HttpStatus.SC_OK) {
        // return null;
        // }
        //
        // is = connection.getInputStream();
        return is;
    }

    /**
     * 使用GET连接指定的url网址，返回结果转为String
     * 
     * @param urlString
     * @return
     */
    public static String doGetString(String urlString) throws IOException {
        InputStream is = null;
        disableConnectionReuseIfNecessary();
        HttpClient client = null;
        client = getHttpClient();

        HttpGet httpGet = bulidHttpGet(urlString);

        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            return null;
        }
        is = response.getEntity().getContent();

        return Utils.convertToString(is);
        // HttpURLConnection connection = null;
        // try {
        //
        // connection = getConnection(urlString);
        // connection.setRequestMethod("GET");
        // connection.connect();
        //
        // final int statusCode = connection.getResponseCode();
        // if (statusCode != HttpStatus.SC_OK) {
        // return null;
        // }
        //
        // is = connection.getInputStream();
        // return Utils.convertToString(is);
        //
        // } finally {
        //
        // if (connection != null) {
        // connection.disconnect();
        // }
        // }
    }

    /**
     * 向指定url发送POST请求，返回结果转为String
     * 
     * @param urlString
     * @param params post请求参数
     * @return
     */
    public static String doPostString(String urlString, Map<String, String> params)
            throws IOException {

        InputStream is = null;

        disableConnectionReuseIfNecessary();
        BufferedReader reader = null;
        DefaultHttpClient client = null;
        StringBuilder result = new StringBuilder();
        // HttpURLConnection connection = null;
        List<NameValuePair> httpParams = new ArrayList<NameValuePair>();
        // 添加要传递的参数
        if (params != null && params.size() > 0) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getValue() != null) {
                    httpParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
        }

        try {
            client = getHttpClient();
            HttpPost httpPost = bulidHttpPost(urlString);
            HttpEntity httpentity = new UrlEncodedFormEntity(httpParams, ENCODEING);
            httpPost.setEntity(httpentity);
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            is = response.getEntity().getContent();
            reader = new BufferedReader(new InputStreamReader(is, ENCODEING), IO_BUFFER_SIZE);
            String buff;
            while ((buff = reader.readLine()) != null) {
                result.append(buff);
            }
            if (statusCode != HttpStatus.SC_OK) {
                LogUtils.e(TAG, "statusCode:" + statusCode + ";content:" + result.toString());
                return null;
            }
        } finally {

            if (reader != null) {
                reader.close();
            }
        }

        return result.toString();

    }

    private static synchronized DefaultHttpClient bulidHttpClient() {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(httpParams, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(httpParams, true);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(httpParams, schReg);

        HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT);
        DefaultHttpClient client = new DefaultHttpClient(conMgr, httpParams);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
        client.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);

        return client;
    }

    private static HttpGet bulidHttpGet(String urlString) {
        HttpGet httpGet = new HttpGet(urlString);

        return httpGet;
    }

    private static DefaultHttpClient httpClient;

    public static DefaultHttpClient getHttpClient() {
        if (httpClient == null) {
            httpClient = bulidHttpClient();
        }
        return httpClient;
    }

    private static HttpPost bulidHttpPost(String urlString) {

        HttpPost httpPost = new HttpPost(urlString);

        return httpPost;
    }

    private static HttpURLConnection getConnection(String urlString) throws IOException {

        HttpURLConnection connection = null;
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        String timestamp = getTimestamp();
        CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);

        return connection;

    }

    /**
     * 修复Froyo之前版本的bug, 具体见:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    private static void disableConnectionReuseIfNecessary() {
        System.setProperty("http.keepAlive", "false");
    }

    private static String getTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        return sdf.format(new Date(System.currentTimeMillis()));
    }

    public static void shutdownHttpClient() {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    

    private NetUtils() {
    }
}
